package org.jmeter.tcp.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;

import java.io.IOException;
import java.util.Map;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/9/8 13:24
 * @since
 */
public class HttpUtil {
    protected static final Logger log = LoggingManager.getLoggerForClass();

    public static CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            return httpClient.execute(request);
        } catch (ClientProtocolException e) {
            log.error("http post error, url is : %s", e);
            throw e;
        } catch (IOException e) {
            log.error("http post error", e);
            throw e;
        }
    }

    public static byte[] parseResponse(CloseableHttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        if (200 == statusCode) {
            byte[] result = EntityUtils.toByteArray(response.getEntity());
            return result;
        } else {
            log.warn(String.format("request fail ! status is: %s", statusCode));
        }
        return null;
    }

    public static byte[] doGet(String url) {
        HttpGet httpGet = new HttpGet(url);

        try {
            CloseableHttpResponse response = execute(httpGet);

            return parseResponse(response);
        } catch (IOException e) {
            log.error("http post error", e);
        }

        return null;
    }

    public static byte[] doPost(String url, Map<String, Object> params) {
        HttpPost post = new HttpPost(url);
        post.setHeader(HTTP.CONTENT_TYPE, "application/json");

        JSONObject jsonObject = new JSONObject(params);
        StringEntity entity = new StringEntity(jsonObject.toString(), "UTF-8");
        post.setEntity(entity);

        try {
            CloseableHttpResponse response = execute(post);

            return parseResponse(response);
        } catch (ClientProtocolException e) {
            log.error("http post error, url is : %s", e);
        } catch (IOException e) {
            log.error("http post error", e);
        }
        return null;
    }

}
